#!/usr/bin/perl -wc

package RFCMail::ESMTP::Object::Mailbox;

use strict;
use Exporter qw(import);
use Carp qw(croak);
use RFCMail::Common::Grammar qw(is_quotable);
use RFCMail::ESMTP::Grammar::Base qw(DOMAIN_RE);
use RFCMail::ESMTP::Grammar::Generator qw(encode_local_part);
use RFCMail::ESMTP::Grammar::Parser qw(split_mailbox);

our @EXPORT_OK = qw(Mailbox);


# Note: function, not method
sub Mailbox {
    my @m = scalar(@_) == 1 ? split_mailbox(@_) : @_;
    return (RFCMail::ESMTP::Object::Mailbox->new(@m));
}


sub new {
    my ($class, $lp, $dp) = @_;
    croak("invalid local-part '$lp'")
	unless defined($lp) and is_quotable($lp);
    croak("invalid domain '$dp'")
	unless defined($dp) and $dp =~ /\A@{[DOMAIN_RE]}\z/o;
    $dp = lc($dp);
    return (bless [$lp, $dp], $class);
}


sub canonical {
    my ($self) = @_;
    my (@new) = @$self;
    $new[0] = lc($new[0])
	if defined($new[0]);
    # Respect the chain of inheritance...
    return (bless \@new, ref($self));
}


sub mailbox {
    my ($self) = @_;
    my ($lp, $dp) = @$self;
    return (encode_local_part($lp).'@'.$dp);
}


sub local_part {
    my ($self) = @_;
    return ($self->[0]);
}


sub domain {
    my ($self) = @_;
    return ($self->[1]);
}


1;
